<?php

declare(strict_types=1);

namespace App\Game\Model;

use Hyperf\Database\Model\Relations\HasMany;
use Hyperf\Database\Model\SoftDeletes;
use Mine\MineModel;

/**
 * @property int $id 主键
 * @property \Carbon\Carbon $created_at 创建时间
 * @property \Carbon\Carbon $updated_at 更新时间
 * @property string $deleted_at 删除时间
 * @property array $name 名称
 * @property string $code 标识
 * @property string $platform 平台
 * @property string $provider provider
 * @property string $icon icon
 * @property string $cover cover
 * @property int $type 1视讯2老虎机3彩票4体育5电竞6捕猎7棋牌
 * @property int $status 1正常
 * @property int $sort 排序
 * @property int $rtp rtp
 * @property string $hall 大厅
 * @property int $demo 0否1是
 * @property int $ingress 支持终端1电脑2手机3电脑/手机网页
 * @property int $view 浏览量
 * @property-read null|\Hyperf\Database\Model\Collection|GameCategory[] $category
 * @property-read null|\Hyperf\Database\Model\Collection|GameTag[] $tag
 */
class Game extends MineModel
{
    use SoftDeletes;

    /**
     * The table associated with the model.
     */
    protected ?string $table = 'game';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'created_at', 'updated_at', 'deleted_at', 'name', 'code', 'platform', 'provider', 'icon', 'cover', 'type', 'status', 'sort', 'rtp', 'hall', 'demo', 'ingress', 'view'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'name' => 'array', 'type' => 'integer', 'status' => 'integer', 'sort' => 'integer', 'rtp' => 'integer', 'demo' => 'integer', 'ingress' => 'integer', 'view' => 'integer'];

    public function getCoverAttribute($v): string
    {
        if ($v) return get_file_url($v);
        if ($this->platform == 'apibet') {
            $path = '/images/game/apibet/' . $this->provider . '/en/' . $this->code . '.webp';
            $file = BASE_PATH . '/public/' . env('UPLOAD_PATH', 'uploadfile') . $path;
            if (file_exists($file)) return get_file_url($path);
            return get_file_url('/images/loading_fail.gif');
        }
        return '';
    }

    public function setCoverAttribute($v): void
    {
        if (!$v) return;
        [, , $key] = get_filesystem();
        $p = parse_url($v);
        $this->attributes['cover'] = $key == 'local' ? str_replace('/' . env('UPLOAD_PATH', 'uploadfile'), '', $p['path']) : $p['path'];
    }

    public function category(): HasMany
    {
        return $this->hasMany(GameCategory::class, 'game_id', 'id');
    }

    public function tag(): HasMany
    {
        return $this->hasMany(GameTag::class, 'game_id', 'id')->with(['tag:id,name,icon']);
    }
}
